#include "stdheader.h"

/////////////////////////////////////////////////////////

CAnimation::CAnimation()
{

}

/////////////////////////////////////////////////////////

CAnimation::~CAnimation()
{

}

/////////////////////////////////////////////////////////

void CAnimation::SetupAnimation(sf::Sprite& tSprite, int iNumRows, int iNumColumns, float fSpeed)
{
	m_fAnimTimer = 0.0f;
	m_fAnimDuration = fSpeed;
	m_iActiveCol = 0;
	m_iActiveRow = 0;
	m_bIdle = true;

	m_iNumCols = iNumColumns;
	m_iNumRows = iNumRows;

	m_tSprite = tSprite;

	m_iRectHeight = tSprite.getGlobalBounds().height / iNumRows;
	m_iRectWidth = tSprite.getGlobalBounds().width / iNumColumns;

	m_tSubRect.top = m_iActiveRow * m_iRectHeight;
	m_tSubRect.left = m_iActiveCol * m_iRectWidth;
	m_tSubRect.height = m_iRectHeight;
	m_tSubRect.width = m_iRectWidth;

	m_tSprite.setTextureRect(m_tSubRect);
}

/////////////////////////////////////////////////////////

void CAnimation::Process(float fTimeDelta)
{
	m_fAnimTimer += fTimeDelta;

	if (m_bIdle)
	{
		m_iActiveCol = m_iNumCols-1;
		m_tSubRect.top = m_iActiveRow * m_iRectHeight;
		m_tSubRect.left = m_iActiveCol * m_iRectWidth;
		m_tSubRect.height = m_iRectHeight;
		m_tSubRect.width = m_iRectWidth;
		m_tSprite.setTextureRect(m_tSubRect);
	}
	else if (m_fAnimTimer > m_fAnimDuration)
	{
		if (m_iNumCols == 1)
			return;

		m_iActiveCol++;

		if (m_iActiveCol > m_iNumCols-2)	// -2 because it starts at zero (so -1), then the final frame is idle, so -1 again 
		{
			m_iActiveCol = 0;
		}

		m_fAnimTimer = 0.0f;
		m_tSubRect.top = m_iActiveRow * m_iRectHeight;
		m_tSubRect.left = m_iActiveCol * m_iRectWidth;
		m_tSubRect.height = m_iRectHeight;
		m_tSubRect.width = m_iRectWidth;
		m_tSprite.setTextureRect(m_tSubRect);

	}
}

/////////////////////////////////////////////////////////

void CAnimation::Render(sf::RenderWindow* pWin)
{
	pWin->draw(m_tSprite);
}

/////////////////////////////////////////////////////////

void CAnimation::SetSprite(sf::Sprite& tSprite) 
{ 
	m_tSprite = tSprite; 
	m_tSubRect.top = m_iActiveRow * m_iRectHeight;
	m_tSubRect.left = m_iActiveCol * m_iRectWidth;
	m_tSubRect.height = m_iRectHeight;
	m_tSubRect.width = m_iRectWidth;
	m_tSprite.setTextureRect(m_tSubRect);
}

/////////////////////////////////////////////////////////

void CAnimation::SetRow(int iRow) 
{ 
	m_iActiveRow = iRow;
	m_tSubRect.top = m_iActiveRow * m_iRectHeight;
	m_tSubRect.left = m_iActiveCol * m_iRectWidth;
	m_tSubRect.height = m_iRectHeight;
	m_tSubRect.width = m_iRectWidth;
	m_tSprite.setTextureRect(m_tSubRect);
}

/////////////////////////////////////////////////////////

void CAnimation::SetIdle(bool bIdle) 
{ 
	m_bIdle = bIdle; 
}

/////////////////////////////////////////////////////////